package co.baiku.boot.common.tools;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.attribute.FileTime;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipTools {

    private ZipTools() {
    }

    public static void write(ZipOutputStream zos, File[] readyToZip)
            throws IOException {
        for (File toZip : readyToZip) {
            addFile(zos, toZip, "");
        }
    }

    private static void addFile(ZipOutputStream out, File f, String base) throws IOException {
        if (f.isDirectory()) {
            File[] listFiles = f.listFiles();
            if (ObjectTools.isNotBlank(listFiles)) {
                ZipEntry entry = new ZipEntry(base + StringTools.VIRGULE);
                FileTime time = FileTime.fromMillis(f.lastModified());
                entry.setLastModifiedTime(time);
                out.putNextEntry(entry);
                base = base.length() == 0 ? "" : base + StringTools.VIRGULE;
                for (File file : listFiles) {
                    if (file.isFile()) {
                        addFile(out, file, base);
                    } else {
                        addFile(out, file, base + file.getName());
                    }
                }
            }
        } else if (f.isFile()) {
            byte[] buf = new byte[8192];
            int len;
            ZipEntry entry = new ZipEntry(base + f.getName());
            FileTime time = FileTime.fromMillis(f.lastModified());
            entry.setLastModifiedTime(time);
            out.putNextEntry(entry);
            try (BufferedInputStream in = new BufferedInputStream(
                    new FileInputStream(f))) {
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
        }
    }

}
